package top.szhome.framework.starter.boot.web;

import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.szhome.framework.core.tools.constant.SzhomeConstant;
import top.szhome.framework.core.tools.support.Resp;
import top.szhome.framework.starter.boot.annotation.DisabledAdvice;

import java.lang.reflect.Method;

/**
 * 响应结果封装
 *
 * @author 唐加利
 * @date 2023/3/15
 **/
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Method method = returnType.getMethod();
        // 防止Swagger接口无法正确返回
        if(!method.getDeclaringClass().getName().startsWith(SzhomeConstant.BASE_PACKAGE)){
            return false;
        }

        Class<?> parameterType = returnType.getParameterType();
        return !Resp.class.isAssignableFrom(parameterType) &&
                AnnotationUtils.findAnnotation(method, DisabledAdvice.class) == null &&
                AnnotationUtils.findAnnotation(method.getDeclaringClass(), DisabledAdvice.class) == null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return Resp.success(body);
    }
}
